package com.david.viewtest.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View


class MyTextView(
    context: Context,
    attrs: AttributeSet,
) : View(context, attrs) {
    val text = "哈哈哈叫啊叫啊哭哭哭叫啊叫啊\n叫姐姐卡啦啦啦啦啦啦\n阿卡啦哦哦啊哦哦啊哦啊哦啦啦啦啦啦啦啦，卡卡卡卡卡."
    val paint = TextPaint()

    private var sl:StaticLayout? = null

    init {
        //paint.textSize = 50f
        paint.textSize =  TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f , resources.displayMetrics)

    }
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val myWidth = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec)

        sl = StaticLayout.Builder.obtain(text, 0,text.length, paint, myWidth).setAlignment(Layout.Alignment.ALIGN_NORMAL).build()

        super.setMeasuredDimension(myWidth, sl?.height ?: 0)
    }
    override fun onDraw(canvas: Canvas) {

        //val width = canvas.width - 100
        //val sl = StaticLayout(text, paint, width, Layout.Alignment.ALIGN_NORMAL, 1f, 1f, false)
        //canvas.save()
        //canvas.translate(50f, 50f)

        canvas.drawText("hahahahha", 10f, 20f, paint)

        canvas.translate(0f, 50f)
        sl?.draw(canvas)
        //canvas.restore()
    }
}